<?php
// application/resources/Translate.php
/**
 * Resource_Translate
 *
 * demo-zf application
 *
 * i18n \ l10n initializer
 *
 * @author Adam Pilacki <adam.pilacki@gmail.com>
 */
final class Resource_Translate
    extends Lib_ResourceAbstract
{

    /**
     * All availabale languages definition
     *
     * @var array
     */
    private static $_validLanguages = array(
        'polish' => 'pl_PL',
        'english' => 'en_GB',
    );

    public static final function isLanguageValid($lang)
    {
//        error_reporting(E_ALL | E_STRICT);
//        echo 'DUMP ' . __METHOD__ . ' line ' . __LINE__ . '<br />';
//        echo '<pre>';
//        var_dump(Zend_Locale::getLocaleList());
//        echo '</pre>';
//        exit();
        return in_array($lang, self::$_validLanguages);
    }

    /**
     * Init translator and store it in registry
     * to get it in app: Zend_Registry::set('translator');
     *
     * @return Zend_Translate
     */
    protected final function _getResource()
    {
        $options = $this->getOptions();

        /* prepare language */
        $session = $this->getBootstrap()->getResource('SessionNamespace');

        if (isset($session->lang)) {
            $lang = $session->lang;
        } else {
            $lang = $session->lang = $options['defaultLang'];
        }

        /* Frontend options - Zend_Cache */
        $frontendOptions = array(
            'lifetime' => $options['cache']['lifetime'], /* Cache lifetime in seconds */
            'automatic_serialization' => true,
            'caching' => $options['cache']['enabled'] /* Cache on/off */
        );

        /* Backend options - Zend_Cache */
        $backendOptions = array(
            'cache_dir' => $options['cache']['dir'], /* Cache dir */
            'file_name_prefix' => $lang /* File prefix */
        );

        /* Set cache for translator */
        Zend_Translate::setCache(Zend_Cache::factory('Page', 'File', $frontendOptions, $backendOptions));

        /* Create Zend_Translate object */
        $translator = new Zend_Translate(
            'gettext',
            APPLICATION_PATH . '/i18n/' . $lang . '/' . Zend_Registry::get('moduleName') . '.mo',
            new Zend_Locale($lang),
            array('scan' => Zend_Translate::LOCALE_FILENAME)
        );
        $translator->addTranslation(APPLICATION_PATH . '/i18n/' . $lang . '/forms.mo', $lang);
        $translator->addTranslation(APPLICATION_PATH . '/i18n/' . $lang . '/resources.mo', $lang);
        $translator->addTranslation(APPLICATION_PATH . '/i18n/' . $lang . '/layouts.mo', $lang);

        /* Store translator in registry */
        Zend_Registry::set('translator', $translator);

        return $translator;
    }
}